package com.pn.controller;

import com.google.code.kaptcha.Producer;
import com.pn.entity.*;
import com.pn.service.AuthService;
import com.pn.service.UserService;
import com.pn.utils.DigestUtil;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@RestController
public class LoginController {

    @Resource(name = "captchaProducer")
    private Producer producer;

    // 注入redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private AuthService authService;


    // 生成验证码图片的接口
    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response) {

        // 生成验证码图片文件
        String text = producer.createText();
        // 使用验证码文本生成验证码图片 -- BufferedImage对象就代表生成的验证码图片，在内存中
        BufferedImage image = producer.createImage(text);
        // 将验证码文本作为键保存到redis -- 设置键的过期时间为30分钟
        redisTemplate.opsForValue().set(text, text, 60 * 30);

        /*
        将验证码响应给前端
         */
        // 设置响应正文image/jpeg
        response.setContentType("image/jpeg");
        // 将验证码图片写给前端
        try (ServletOutputStream out = response.getOutputStream()) {
            // 使用响应对象的字节输出流写入验证码图片，自然是给前端写入
            ImageIO.write(image, "jpg", out);
            // 刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 登录的url接口
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser) {

        String code = loginUser.getVerificationCode();

        if (!redisTemplate.hasKey(code)) {
            return Result.err(Result.CODE_ERR_BUSINESS, "验证码错误！");
        }

        User user = userService.queryUserByCode(loginUser.getUserCode());

        if (user != null) {
            if (user.getUserState().equals(WarehouseConstants.USER_STATE_PASS)) {
                String userPwd = loginUser.getUserPwd();
                // 进行md5加密和数据库密码比对
                userPwd = DigestUtil.hmacSign(userPwd);

                if (user.getUserPwd().equals(userPwd)) {
                    // 生成jwt token,并存到redis
                    CurrentUser currentUser =
                            new CurrentUser(user.getUserId(), user.getUserCode(), user.getUserName());

                    String token = tokenUtils.loginSign(currentUser, userPwd);

                    // 向客户端响应jwt token
                    return Result.ok("登陆成功！", token);

                } else {

                    return Result.err(Result.CODE_ERR_BUSINESS, "密码错误！");
                }
            } else {

                return Result.err(Result.CODE_ERR_BUSINESS, "用户未审核！");
            }
        } else {

            return Result.err(Result.CODE_ERR_BUSINESS, "账号不存在！");
        }
    }

    /*
     获取当前登录用户信息的接口
     参数 @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     表示将请求头Token的值(前端归还的token赋值给请求处理方法入参变量token)
     */
    @RequestMapping("/curr-user")
    public Result currentUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {

        CurrentUser currentUser = tokenUtils.getCurrentUser(token);

        return Result.ok(currentUser);
    }


    /*
     加载用户权限菜单树的url接口/user/auth-list
     */
    @RequestMapping("/user/auth-list")
    public Result loadAuthTree(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {

        // 拿到当前登录的用户id
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int userId = currentUser.getUserId();

        // 执行业务
        List<Auth> authTreeList = authService.authTreeByUid(userId);

        // 响应
        return Result.ok(authTreeList);

    }

    /*
    登出的url接口/logout
     */
    @RequestMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        // 从redis删除token的键
        redisTemplate.delete(token);
        // 响应
        return Result.ok("退出系统");
    }

}
